#测试模块调用的方法
"""
# 导入自定义模块
import mymodule as mm

# 调用函数
mm.say_hello("zhaoshicong")

# 创建类对象并调用方法
greeter = mm.Greeter("Python开发者")
greeter.greet()
"""

#判断当前摄像头是否支持分辨率的枚举
'''
import cv2
# 常见分辨率列表
resolutions = [
    (160, 120), (320, 240), (640, 480),
    (800, 600), (1024, 768), (1280, 720),
    (1920, 1080), (2560, 1440), (3840, 2160)
]

cap = cv2.VideoCapture(0)  # 打开默认摄像头

for width, height in resolutions:
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

    actual_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    actual_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)

    if int(actual_width) == width and int(actual_height) == height:
        print(f"支持分辨率: {width}x{height}")
    else:
        print(f"不支持 {width}x{height}, 实际设置为 {int(actual_width)}x{int(actual_height)}")

cap.release()
'''

#在脸上绘制出关键点的编号，对mediapipe是有用的
'''
import cv2
import mediapipe as mp

mp_face_mesh = mp.solutions.face_mesh
mp_drawing = mp.solutions.drawing_utils

# 绘制参数
drawing_spec = mp_drawing.DrawingSpec(color=(0,255,0), thickness=1, circle_radius=1)

# 打开摄像头
cap = cv2.VideoCapture(0)

cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)

with mp_face_mesh.FaceMesh(
    max_num_faces=1,              # 只检测 1 张人脸
    refine_landmarks=True,        # 是否包含虹膜（478 点）
    min_detection_confidence=0.5,
    min_tracking_confidence=0.5
) as face_mesh:

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break

        # BGR → RGB
        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        results = face_mesh.process(rgb)

        if results.multi_face_landmarks:
            for face_landmarks in results.multi_face_landmarks:
                h, w, _ = frame.shape  # 获取图像尺寸

                # 遍历 468 (或 478) 个点
                for idx, lm in enumerate(face_landmarks.landmark):
                    x, y = int(lm.x * w), int(lm.y * h)

                    # 画一个小圆点
                    cv2.circle(frame, (x, y), 1, (0, 255, 0), -1)

                    # 在点旁边写编号
                    cv2.putText(frame, str(idx), (x, y),
                                cv2.FONT_HERSHEY_SIMPLEX,
                                0.3, (0, 0, 255), 1, cv2.LINE_AA)

        cv2.imshow('FaceMesh Landmarks', frame)
        if cv2.waitKey(1) & 0xFF == 27:  # 按 ESC 退出
            break
cap.release()
cv2.destroyAllWindows()
'''

#绘制眼球上虹膜关键点：
"""
import cv2
import mediapipe as mp

mp_drawing = mp.solutions.drawing_utils
mp_face_mesh = mp.solutions.face_mesh

drawing_spec = mp_drawing.DrawingSpec(color=(0,255,0), thickness=1, circle_radius=1)

with mp_face_mesh.FaceMesh(
    max_num_faces=1,
    refine_landmarks=True,   # ⚠️ 这一行必须打开，才会输出虹膜点
    min_detection_confidence=0.5,
    min_tracking_confidence=0.5) as face_mesh:

    cap = cv2.VideoCapture(0)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 2560)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1440)
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break

        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        results = face_mesh.process(rgb)

        if results.multi_face_landmarks:
            for landmarks in results.multi_face_landmarks:
                mp_drawing.draw_landmarks(
                    frame,
                    landmarks,
                    mp_face_mesh.FACEMESH_IRISES,   # 👈 绘制虹膜
                    None, drawing_spec
                )
                
        cv2.imshow('FaceMesh Iris', frame)
        if cv2.waitKey(1) & 0xFF == 27:
            break

    cap.release()
    cv2.destroyAllWindows()

"""
#用openCV来调节画面对比度颜色等
"""

import cv2
import numpy as np
cv2.namedWindow("Adjusted")
def nothing(x):
    pass
cap = cv2.VideoCapture(0)
# 创建一个窗口
cv2.namedWindow("Adjusted")

# 创建滑动条
cv2.createTrackbar("Brightness", "Adjusted", 50, 100, nothing)  # 亮度 -50~+50
cv2.createTrackbar("Contrast", "Adjusted", 10, 30, nothing)     # 对比度 0.0~3.0
cv2.createTrackbar("Saturation", "Adjusted", 50, 100, nothing)  # 饱和度 0.0~2.0

while True:
    ret, frame = cap.read()
    if not ret:
        break

    # 获取滑动条数值
    brightness = cv2.getTrackbarPos("Brightness", "Adjusted") - 50
    contrast = cv2.getTrackbarPos("Contrast", "Adjusted") / 10.0
    saturation = cv2.getTrackbarPos("Saturation", "Adjusted") / 50.0

    # 调节亮度 + 对比度
    adjusted = cv2.convertScaleAbs(frame, alpha=contrast, beta=brightness)

    # 调节饱和度 (转 HSV 修改 S 通道)
    hsv = cv2.cvtColor(adjusted, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(hsv)
    s = cv2.convertScaleAbs(s, alpha=saturation, beta=0)
    hsv = cv2.merge([h, s, v])
    adjusted = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

    # 显示结果
    cv2.imshow("Original", frame)
    cv2.imshow("Adjusted", adjusted)

    # 按 ESC 退出
    if cv2.waitKey(1) & 0xFF == 27:
        break
cap.release()
cv2.destroyAllWindows()
"""


#用opencv + pyqt5来UI展示调节效果功能

"""
import sys
import cv2
import numpy as np
from PyQt5.QtWidgets import (
    QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QHBoxLayout,
    QSlider, QFileDialog, QGroupBox, QGridLayout
)
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import QTimer, Qt


class CameraApp(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PyQt5 + OpenCV 摄像头控制面板 Demo")
        self.resize(1000, 600)

        # 摄像头
        self.cap = cv2.VideoCapture(0)

        # 控制开关
        self.gray_mode = False
        self.edge_mode = False
        self.flip_mode = False

        # 界面布局
        layout = QHBoxLayout(self)

        # 左侧控制面板
        control_panel = QVBoxLayout()

        # ========== 按钮区 ==========
        btn_group = QGroupBox("功能按钮")
        btn_layout = QVBoxLayout()
        self.btn_gray = QPushButton("切换灰度")
        self.btn_edge = QPushButton("切换边缘检测")
        self.btn_flip = QPushButton("切换翻转")
        self.btn_save = QPushButton("保存当前帧")
        self.btn_exit = QPushButton("退出")

        self.btn_gray.clicked.connect(self.toggle_gray)
        self.btn_edge.clicked.connect(self.toggle_edge)
        self.btn_flip.clicked.connect(self.toggle_flip)
        self.btn_save.clicked.connect(self.save_frame)
        self.btn_exit.clicked.connect(self.close)

        for b in [self.btn_gray, self.btn_edge, self.btn_flip, self.btn_save, self.btn_exit]:
            btn_layout.addWidget(b)

        btn_group.setLayout(btn_layout)
        control_panel.addWidget(btn_group)

        # ========== 滑动条区 ==========
        slider_group = QGroupBox("图像调节")
        slider_layout = QGridLayout()

        self.slider_brightness = self.create_slider(-50, 50, 0)
        self.slider_contrast = self.create_slider(10, 30, 10)
        self.slider_saturation = self.create_slider(0, 100, 50)
        self.slider_gamma = self.create_slider(10, 300, 100)

        slider_layout.addWidget(QLabel("亮度"), 0, 0)
        slider_layout.addWidget(self.slider_brightness, 0, 1)
        slider_layout.addWidget(QLabel("对比度"), 1, 0)
        slider_layout.addWidget(self.slider_contrast, 1, 1)
        slider_layout.addWidget(QLabel("饱和度"), 2, 0)
        slider_layout.addWidget(self.slider_saturation, 2, 1)
        slider_layout.addWidget(QLabel("Gamma"), 3, 0)
        slider_layout.addWidget(self.slider_gamma, 3, 1)

        slider_group.setLayout(slider_layout)
        control_panel.addWidget(slider_group)

        control_panel.addStretch()

        # 右侧视频显示
        self.label = QLabel()
        self.label.setFixedSize(800, 600)

        layout.addLayout(control_panel)
        layout.addWidget(self.label)

        # 定时器读取摄像头
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(30)  # 30ms 刷新一次

    def create_slider(self, min_val, max_val, init_val):
        slider = QSlider(Qt.Horizontal)
        slider.setMinimum(min_val)
        slider.setMaximum(max_val)
        slider.setValue(init_val)
        return slider

    # ====== 按钮逻辑 ======
    def toggle_gray(self):
        self.gray_mode = not self.gray_mode

    def toggle_edge(self):
        self.edge_mode = not self.edge_mode

    def toggle_flip(self):
        self.flip_mode = not self.flip_mode

    def save_frame(self):
        ret, frame = self.cap.read()
        if ret:
            filename, _ = QFileDialog.getSaveFileName(self, "保存图片", "", "PNG Files (*.png);;JPG Files (*.jpg)")
            if filename:
                cv2.imwrite(filename, frame)
                print("已保存:", filename)

    # ====== 图像更新逻辑 ======
    def update_frame(self):
        ret, frame = self.cap.read()
        if not ret:
            return

        # 翻转 每帧都在检测的
        if self.flip_mode:
            frame = cv2.flip(frame, 1)

        # 灰度
        if self.gray_mode:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)

        # 边缘检测
        if self.edge_mode:
            edges = cv2.Canny(frame, 100, 200)
            frame = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)

        # ====== 滑动条调节 ======
        brightness = self.slider_brightness.value()
        contrast = self.slider_contrast.value() / 10.0
        saturation = self.slider_saturation.value() / 50.0
        gamma = self.slider_gamma.value() / 100.0

        # 亮度 + 对比度
        frame = cv2.convertScaleAbs(frame, alpha=contrast, beta=brightness)

        # 饱和度调整
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        h, s, v = cv2.split(hsv)
        s = cv2.convertScaleAbs(s, alpha=saturation, beta=0)
        hsv = cv2.merge([h, s, v])
        frame = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

        # Gamma 调整
        inv_gamma = 1.0 / gamma
        table = np.array([(i / 255.0) ** inv_gamma * 255 for i in np.arange(256)]).astype("uint8")
        frame = cv2.LUT(frame, table)

        # 转 Qt 图像
        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        h, w, ch = rgb.shape
        qimg = QImage(rgb.data, w, h, ch * w, QImage.Format_RGB888)
        self.label.setPixmap(QPixmap.fromImage(qimg))

    def closeEvent(self, event):
        self.cap.release()
        super().closeEvent(event)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = CameraApp()
    win.show()
    sys.exit(app.exec_())
"""